/**
 * Copyright (C) 2015-2018 IQIYI
 * All rights reserved.
 *
 * AUTHOR(S)
 * 王海斌
 *   E-mail: wanghaibin@qiyi.com
 * 
 * VERSION
 *   Tue 03 Jul 2018 02:12:39 PM CST
 */
#include <stdio.h>
#include <vector>
#include <string>
#include <sys/types.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <string.h>

void GetLocalIps(std::vector<std::string> &ips, bool bIpV6)
{
    struct ifaddrs *ifAddrStruct = NULL, *tmpAddrs = NULL;
    void *tmpAddrPtr = NULL;
    getifaddrs(&ifAddrStruct);
    if (NULL == ifAddrStruct) {
        return;
    } else {
        tmpAddrs = ifAddrStruct; //ָв¿ªʼλ׃
    }
    while (ifAddrStruct != NULL) {
        if (ifAddrStruct->ifa_addr->sa_family == AF_INET && !bIpV6) {
            tmpAddrPtr = &((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
            char addressBuffer[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
            if (0 != strcmp(addressBuffer, "127.0.0.1")) {
                ips.push_back(addressBuffer);
            }
        } else if (ifAddrStruct->ifa_addr->sa_family == AF_INET6 && bIpV6) {
            tmpAddrPtr = &((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
            char addressBuffer[INET6_ADDRSTRLEN];
            inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
            if (0 != strcmp(addressBuffer, "::")) {
                ips.push_back(addressBuffer);
            }
        }
        ifAddrStruct = ifAddrStruct->ifa_next;
    }
    if (tmpAddrs) {
        freeifaddrs(tmpAddrs);
    }
}


#include <sstream>

/*-----------------------------------------
 * 局域网IP地址范围
 * A类：10.0.0.0-10.255.255.255
 * B类：172.16.0.0-172.31.255.255 
 * C类：192.168.0.0-192.168.255.255
 * -------------------------------------------*/
bool isLAN(const std::string& ipstring)
{
    std::istringstream st(ipstring);
    int ip[2];
    for(int i = 0; i < 2; i++)
    {
        std::string temp;
        getline(st,temp,'.');
        std::istringstream a(temp);
        a >> ip[i];
    }
    if((ip[0]==10) ||
            (ip[0]==172 && ip[1]>=16 && ip[1]<=31) ||
            (ip[0]==192 && ip[1]==168))
        return true;
    else return false;
}

int main(int argc, char *argv[])
{
    std::vector<std::string> ips;
    GetLocalIps(ips, false);
    for(size_t i=0; i<ips.size(); ++i) {
        printf("ip=%s isLan=%d\n", ips[i].c_str(), isLAN(ips[i]));
    }
    return 0;
}
